package webapp.mvc.services.impl;

import org.springframework.stereotype.Service;
import webapp.mvc.enums.IntBooleans;
import webapp.mvc.exceptions.CategoryException;
import webapp.mvc.finders.ShopCategoryFinder;
import webapp.mvc.models.ShopCategoryEntity;
import webapp.mvc.models.ShopEntity;
import webapp.mvc.services.ICategoryService;

import java.util.List;

@Service
public class CategoryService implements ICategoryService {
    @Override
    public ShopCategoryEntity findById(String id) {
        return ShopCategoryEntity.find.byId(id);
    }

    public List<ShopCategoryEntity> getShopCategories() {
        return ShopCategoryEntity.find.list();
    }

    @Override
    public ShopCategoryEntity createShopCategory(String name, String logoUrl) throws CategoryException {
        ShopCategoryEntity shopCategoryEntity = ShopCategoryEntity.find.findByName(name);
        if(shopCategoryEntity != null) {
            throw new CategoryException("此商户分类名称已经存在");
        }
        logoUrl = logoUrl!=null?logoUrl:"";
        shopCategoryEntity = new ShopCategoryEntity();
        shopCategoryEntity.setName(name);
        shopCategoryEntity.setLogoUrl(logoUrl);
        shopCategoryEntity.save();
        return shopCategoryEntity;
    }

    @Override
    public ShopCategoryEntity deleteShopCategory(ShopCategoryEntity shopCategoryEntity) throws CategoryException {
        if(shopCategoryEntity == null) {
            return null;
        }
        // 如果当前有商户使用此分类,就不允许删除此分类
        if(ShopEntity.find.where()
                .eq("categoryId", shopCategoryEntity.getId())
                .eq("deleted", IntBooleans.FALSE).first() != null) {
            throw new CategoryException("有商户正在使用此分类,无法删除此商户分类");
        }
        shopCategoryEntity.setDeleted(IntBooleans.TRUE);
        shopCategoryEntity.update();
        return shopCategoryEntity;
    }

    @Override
    public ShopCategoryEntity findShopCategoryByName(String name) {
        return ShopCategoryEntity.find.findByName(name);
    }
}
